import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

mixin PullToRefresh<T> {
  ///分页
  RefreshController refreshController = RefreshController(initialRefresh: false);

  ///当前页数
  int _page = 0;

  ///每页的数量
  int num = 15;

  ///列表的key
  String getListKeyName();

  ///第一页加载完是否需要显示空视图
  bool canShowEmpty = false;

  ///请求方式
  String method() => 'GET';

  ///解析list中的item
  T decodeJson(dynamic json);

  ///接口返回的原数据
  Future? originJson(dynamic json) {}

  ///返回接口的api
  Future<CommonApi> getApi();

  ///接口返回的数据
  void loadResult(bool isFirstPage, List<T> temp, dynamic originalJson);

  ///自动刷新
  void _refreshDataAnim() => refreshController.requestRefresh();

  ///一般用于initState中
  void firstDataAnim() {
    SchedulerBinding.instance.addPostFrameCallback((_) => _refreshDataAnim());
  }

  void firstDataProgress() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      Loading.show();
      refreshData();
    });
  }

  ///请求刷新的回调
  void refreshData() {
    _page = 0;
    loadMoreData();
  }

  ///请求加载更多的回调
  Future loadMoreData() async {
    _page++;
    List<T> temp = [];
    dynamic originalJson;
    try {
      CommonApi api = await getApi();
      api.params.addAll({'page': _page});
      dynamic json = (method() == 'GET') ? await CommonNet.get(api) : await CommonNet.post(api);
      originalJson = json;
      await originJson(json);
      canShowEmpty = true;
      if (getListKeyName().notEmpty) {
        temp = await CommonJson.getList(json, decodeJson, keyName: getListKeyName());
      }
      if (json['size'] != null) {
        num = int.tryParse(json['size']) ?? 15;
      }
      Loading.dismiss();
    } catch (e) {
      Log.log("loadMoreData ::: e= ${e.toString()}");
      if (_page == 1) {
        refreshController.refreshFailed();
      } else {
        refreshController.loadFailed();
      }
      Loading.dismiss();
      return;
    }

    Log.log("page = $_page, curCount = ${temp.length}");

    if (temp.length < num) {
      if (_page == 1) {
        refreshController.refreshCompleted();
      }
      refreshController.loadNoData();
    } else {
      if (_page == 1) {
        refreshController.refreshCompleted(resetFooterState: true);
      } else {
        refreshController.loadComplete();
      }
    }

    loadResult(_page == 1, temp, originalJson);
  }

  Widget getRefresh({
    required Widget child,
    bool enablePullDown = true,
    bool enablePullUp = true,
  }) {
    return SmartRefresher(
      enablePullDown: enablePullDown,
      enablePullUp: enablePullUp,
      header: const ClassicHeader(
        releaseText: '松开手刷新',
        refreshingText: '刷新中',
        completeText: '刷新完成',
        failedText: '刷新失败',
        idleText: '下拉刷新',
      ),
      footer: const ClassicFooter(
        idleText: '加载更多',
        loadingText: '加载中',
        noDataText: '已到底',
        failedText: '加载失败，请重试',
      ),
      controller: refreshController,
      onRefresh: refreshData,
      onLoading: loadMoreData,
      child: child,
    );
  }
}
